<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <right-toolbar @query-table="search" />
    </el-row>
    <el-table v-loading="loading" :data="deploymentList">
      <el-table-column label="流程名称" prop="name" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="流程编码" prop="key" :show-overflow-tooltip="true" min-width="180" />
      <el-table-column label="流程ID" prop="id" width="240" />
      <el-table-column label="部署ID" prop="deploymentId" width="240" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="lastUpdateTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastUpdateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400px" fixed="right">
        <template #default="scope">
          <div class="operation">
            <text-button text="查看流程图" icon="Document" @click="showFlowStaticImg(scope.row)" />
            <text-button text="下载BPMN20" icon="Download" @click="downloadHandler(scope.row)" />
            <text-danger-button
              text="撤销发布"
              icon="Close"
              @click="revokePublish(scope.row)"
              :message="`是否确认撤销已发布的流程[${scope.row.name}(${scope.row.key})]，撤销后流程将不可用，可通过流程定义再次发布?`"
            />
            <el-dropdown @command="(command) => handleConf(command, scope.row)">
              <span class="ml10 operation-drop">
                <text-button text="流程配置" /><el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="confBut" icon="el-icon-setting"
                  >按钮配置</el-dropdown-item
                  >
                  <el-dropdown-item command="confUrl" icon="el-icon-document"
                  >页面配置</el-dropdown-item
                  >
                  <el-dropdown-item command="confApprove" icon="el-icon-coordinate"
                  >审批配置</el-dropdown-item
                  >
                  <el-dropdown-item command="confAuth" icon="el-icon-user"
                  >授权配置</el-dropdown-item
                  >
                  <el-dropdown-item command="confEvent" icon="el-icon-user"
                  >事件配置</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="search"
    />
    <!-- 配置按钮 -->
    <drag-dialog
      :title="configButtonsPage.title"
      :close-on-click-modal="false"
      v-model="configButtonsPage.open"
      width="80%"
      append-to-body
      @close="cancelConfigButtons"
    >
      <div class="scrollable-content">
        <bpmn-viewer v-if="isFlowable && configButtonsPage.open" :modelId="modelId" :deploymentId="deploymentId" />
        <wf-static-image v-else :modelId="modelId" />
        <el-form :inline="true">
          <el-divider />
          <el-row style="line-height: 36px">
            <el-col :span="4">审批节点名称</el-col>
            <el-col :span="20">审批页面按钮</el-col>
          </el-row>
          <el-divider />
          <el-form-item v-for="(node, idx) in deploymentInfo.elements" :key="idx">
            <el-row>
              <el-col :span="4">{{ node.taskName }}</el-col>
              <el-col :span="20">
                <el-checkbox
                  v-for="(btn, index2) in deploymentInfo.buttons"
                  :key="index2"
                  :name="node.taskId + ':' + btn.code"
                  :label="btn.name + '(' + btn.code + ')'"
                  style="width: 200px"
                  v-model="configButtonsPage.checkedButtons[node.taskId + ':' + btn.code]"
                />
              </el-col>
            </el-row>
            <el-divider />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitHandlerButtons">确 定</el-button>
          <el-button @click="configButtonsPage.open = false">取 消</el-button>
        </div>
      </template>
    </drag-dialog>
    <!-- 配置页面 -->
    <drag-dialog
      :title="configUrlsPage.title"
      :close-on-click-modal="false"
      v-model="configUrlsPage.open"
      width="80%"
      append-to-body
      @close="cancelConfigUrls"
    >
      <div class="scrollable-content">
        <bpmn-viewer v-if="isFlowable && configUrlsPage.open" :deploymentId="deploymentId" />
        <wf-static-image v-else :modelId="modelId" />
        <el-form :inline="false" label-width="240px">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1">
              <template #title> <el-tag type="info">低</el-tag>【引擎级】页面配置 </template>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="待办审批页面URL:">
                    {{ configUrlsPage.approveUrl || '[未配置]' }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="待办审批页面内嵌URL:">
                    {{ configUrlsPage.approveFrameUrl || '[未配置]' }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="已办查看页面URL:">
                    {{ configUrlsPage.doneViewUrl || '[未配置]' }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="已办查看页面内嵌URL:">
                    {{ configUrlsPage.doneViewFrameUrl || '[未配置]' }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="发起查看页面URL:">
                    {{ configUrlsPage.startViewUrl || '[未配置]' }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发起查看页面内嵌URL:">
                    {{ configUrlsPage.startViewFrameUrl || '[未配置]' }}
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
            <el-collapse-item name="2">
              <template #title> <el-tag type="warning">中</el-tag>【流程级】页面配置 </template>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="待办审批页面URL:">
                    <el-input v-model="configUrlsPage.wfApproveUrl" clearable>
                      <template #append>
                        <el-button icon="el-icon-search" @click="handlePageSelectOpen('flow','wfApproveUrl')" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="待办审批页面内嵌URL:">
                    <el-input v-model="configUrlsPage.wfApproveFrameUrl" clearable>
                      <template #append>
                        <el-button icon="el-icon-search" @click="handlePageSelectOpen('flow','wfApproveFrameUrl')" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="已办查看页面URL:">
                    <el-input v-model="configUrlsPage.wfDoneViewUrl" clearable>
                      <template #append>
                        <el-button icon="el-icon-search" @click="handlePageSelectOpen('flow','wfDoneViewUrl')" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="已办查看页面内嵌URL:">
                    <el-input v-model="configUrlsPage.wfDoneViewFrameUrl" clearable>
                      <template #append>
                        <el-button icon="el-icon-search" @click="handlePageSelectOpen('flow','wfDoneViewFrameUrl')" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="发起查看页面URL:">
                    <el-input v-model="configUrlsPage.wfStartViewUrl" clearable>
                      <template #append>
                        <el-button icon="el-icon-search" @click="handlePageSelectOpen('flow','wfStartViewUrl')" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发起查看页面内嵌URL:">
                    <el-input v-model="configUrlsPage.wfStartViewFrameUrl" clearable>
                      <template #append>
                        <el-button icon="el-icon-search" @click="handlePageSelectOpen('flow','wfStartViewFrameUrl')" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
            <el-collapse-item name="3">
              <template #title> <el-tag type="danger">高</el-tag>【节点级】页面配置 </template>
              <el-row>
                <el-col :span="24" class="node-table">
                  <el-row>
                    <el-col :span="4" class="label">审批节点名称</el-col>
                    <el-col :span="4" class="label">流程自定义表单</el-col>
                    <el-col :span="4" class="label">审批页面URL</el-col>
                    <el-col :span="4" class="label">审批页面内嵌URL</el-col>
                    <el-col :span="4" class="label">已办页面URL</el-col>
                    <el-col :span="4" class="label">已办页面内嵌URL</el-col>
                  </el-row>
                  <el-divider />
                  <el-row :gutter="4" v-for="(node, index) in deploymentInfo.elements" :key="index">
                    <el-col :span="4" class="label">
                      <span class="label-text">{{ node.taskName }}({{ node.taskId }})</span>
                    </el-col>
                    <el-col :span="4" class="label disabled">{{ node.formKey || '[未配置]' }}</el-col>
                    <el-col :span="4">
                      <el-input v-model="configUrlsPage.nodeApproveUrl[node.taskId]" clearable>
                        <template #append>
                          <el-button icon="el-icon-search" @click="handlePageSelectOpen('node','nodeApproveUrl',node.taskId)" />
                        </template>
                      </el-input>
                    </el-col>
                    <el-col :span="4">
                      <el-input v-model="configUrlsPage.nodeApproveFrameUrl[node.taskId]" clearable>
                        <template #append>
                          <el-button icon="el-icon-search" @click="handlePageSelectOpen('node','nodeApproveFrameUrl',node.taskId)" />
                        </template>
                      </el-input>
                    </el-col>
                    <el-col :span="4">
                      <el-input v-model="configUrlsPage.nodeDoneViewUrl[node.taskId]" clearable>
                        <template #append>
                          <el-button icon="el-icon-search" @click="handlePageSelectOpen('node','nodeDoneViewUrl',node.taskId)" />
                        </template>
                      </el-input>
                    </el-col>
                    <el-col :span="4">
                      <el-input
                        v-model="configUrlsPage.nodeDoneViewFrameUrl[node.taskId]"
                        clearable
                      >
                        <template #append>
                          <el-button icon="el-icon-search" @click="handlePageSelectOpen('node','nodeDoneViewFrameUrl',node.taskId)" />
                        </template>
                      </el-input>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-collapse-item>
            <el-collapse-item name="4">
              <template #title>
                <el-icon><InfoFilled /></el-icon>
                <!-- <i class="el-icon-info"></i> -->
                优先级说明
              </template>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="审批页面优先级:">
                    <strong>
                      <mark>【节点级】审批页面URL</mark>&nbsp;&gt;&nbsp;
                      <mark>【流程级】审批页面URL</mark>&nbsp;&gt;&nbsp;
                      <mark>【引擎级】审批页面URL</mark>
                    </strong>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="内嵌页面优先级:">
                    <strong>
                      <mark>【节点级】审批页面内嵌URL</mark>&nbsp;&gt;&nbsp;
                      <mark>【流程级】审批页面内嵌URL</mark>&nbsp;&gt;&nbsp;
                      <mark>【流程级】自定义表单</mark>&nbsp;&gt;&nbsp;
                      <mark>【引擎级】审批页面内嵌URL</mark>
                    </strong>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitHandlerUrls">确 定</el-button>
          <el-button @click="configUrlsPage.open = false">取 消</el-button>
        </div>
      </template>
    </drag-dialog>

    <!-- 配置approve -->
    <drag-dialog
      :title="configApprovePage.title"
      :close-on-click-modal="false"
      v-model="configApprovePage.open"
      width="80%"
      append-to-body
      @close="cancelConfigApprove"
    >
      <div class="scrollable-content">
        <bpmn-viewer v-if="isFlowable && configApprovePage.open" :deploymentId="deploymentId" />
        <wf-static-image v-else :modelId="modelId" />
        <h4>
          流程名称：<span>{{ deploymentInfo.name }}</span
          >(<span>{{ deploymentInfo.key }}</span
          >)
        </h4>
        <el-form :inline="false" label-width="10px">
          <el-divider />
          <el-row>
            <el-col :span="24">
              <el-form-item class="node-table">
                <el-row>
                  <el-col :span="6" class="label">审批节点名称</el-col>
                  <el-col :span="6" class="label">是否可批量审批</el-col>
                  <el-col :span="6" class="label">参与人选择方式</el-col>
                  <el-col :span="6" class="label">消息发送方式</el-col>
                </el-row>
                <el-divider />
                <el-row :gutter="6" v-for="(node, idx) in deploymentInfo.elements" :key="idx">
                  <el-col :span="6" class="label">{{ node.taskName }}({{ node.taskId }})</el-col>
                  <el-col :span="6" class="label">
                    <el-select v-model="configApprovePage.canBatchApprove[node.taskId]" size="small">
                      <el-option
                        v-for="dict in configApprovePage.canBatchOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="6" class="label">
                    <el-select
                      v-model="configApprovePage.candidateSelectType[node.taskId]"
                      size="default"
                    >
                      <el-option
                        v-for="dict in configApprovePage.selectTypeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="6" class="label">
                    <el-select
                      v-model="configApprovePage.messageSendType[node.taskId]"
                      size="default"
                    >
                      <el-option
                        v-for="dict in configApprovePage.sendTypeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitHandlerApprove">确 定</el-button>
          <el-button @click="configApprovePage.open = false">取 消</el-button>
        </div>
      </template>
    </drag-dialog>

    <!-- 配置授权 -->
    <drag-dialog :title="configAuthPage.title" :close-on-click-modal="false" v-model="configAuthPage.open" width="60%" append-to-body @close="cancelConfigAuth">
      <div class="scrollable-content">
        <span>开启授权使用：</span>
        <el-switch :model-value="configAuthPage.enableAuth" active-value="Y" inactive-value="N" @change="handleEnableAuth" />
        <el-tabs type="border-card" v-model="configAuthPage.dataParams.authType" @tab-click="handleAuthType">
          <el-tab-pane :disabled="configAuthPage.enableAuth !== 'Y'" label="人员授权" name="01">
            <el-form :model="configAuthPage.userParams" :inline="true" label-width="100px">
              <el-form-item label="登录名：">
                <el-input v-model="configAuthPage.userParams.loginNameLike" clearable size="default" style="width: 200px" />
              </el-form-item>
              <el-form-item label="用户姓名：">
                <el-input v-model="configAuthPage.userParams.userNameLike" clearable size="default" style="width: 200px" />
              </el-form-item>
              <el-form-item>
                <search-button @click="handleAuthQuery" />
                <reset-button @click="resetAuthQuery" />
              </el-form-item>
            </el-form>
            <br />
            <el-row :gutter="10" class="mb8">
              <add-button @click="selectAuthInfo" text="选择" />
              <delete-button @click="handleDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
            </el-row>
            <el-table :data="configAuthPage.authUserDataList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="登录名" align="center" prop="loginName" min-width="120" />
              <el-table-column label="用户姓名" align="center" prop="userName" min-width="120" />
              <el-table-column label="公司/部门" align="center" min-width="120">
                <template #default="scope">
                  {{ (scope.row.companyName || '-') + ' / ' + (scope.row.deptName || '-') }}
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" min-width="120">
                <template #default="scope">
                  <el-popover v-if="scope.row.status === '2'" placement="top-start" width="240" trigger="hover" title="用户已锁定">
                    <template #reference>
                      <el-tag type="warning">锁定</el-tag>
                    </template>
                  </el-popover>
                  <el-tag v-else :type="scope.row.status === '0' ? 'success' : 'danger'" disable-transitions>
                    {{ scope.row.status === '0' ? '正常' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="100" fixed="right">
                <template #default="scope">
                  <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.loginName + '?'" />
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="configAuthPage.total > 0"
              :total="configAuthPage.total"
              v-model:page="configAuthPage.userParams.pageNum"
              v-model:limit="configAuthPage.userParams.pageSize"
              @pagination="getUserAuthList"
            />
            <OrgPicker ref="orgPicker" @ok="doSelected"></OrgPicker>
          </el-tab-pane>
          <el-tab-pane :disabled="configAuthPage.enableAuth !== 'Y'" label="部门授权" name="02">
            <el-form :model="configAuthPage.deptParams" :inline="true" label-width="100px">
              <el-form-item label="部门名称：">
                <el-input v-model="configAuthPage.deptParams.deptNameLike" clearable size="default" style="width: 200px" />
              </el-form-item>
              <el-form-item>
                <search-button @click="handleAuthQuery" />
                <reset-button @click="resetAuthQuery" />
              </el-form-item>
            </el-form>
            <br />
            <el-row :gutter="10" class="mb8">
              <add-button @click="selectAuthInfo" text="选择" />
              <delete-button @click="handleDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
            </el-row>
            <el-table :data="configAuthPage.authDeptDataList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="部门名称" align="center" prop="deptName" min-width="120" />
              <el-table-column label="部门编码" align="center" prop="deptCode" min-width="120" />
              <el-table-column label="简称" align="center" prop="deptShortname" min-width="120" />
              <el-table-column label="状态" align="center" min-width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                    {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="100" fixed="right">
                <template #default="scope">
                  <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.deptName + '?'" />
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="configAuthPage.total > 0"
              :total="configAuthPage.total"
              v-model:page="configAuthPage.deptParams.pageNum"
              v-model:limit="configAuthPage.deptParams.pageSize"
              @pagination="getDeptAuthList"
            />
            <DeptPicker ref="deptPicker" @ok="doSelected"></DeptPicker>
          </el-tab-pane>
          <el-tab-pane :disabled="configAuthPage.enableAuth !== 'Y'" label="公司授权" name="03">
            <el-form :model="configAuthPage.companyParams" :inline="true" label-width="100px">
              <el-form-item label="公司名称：">
                <el-input v-model="configAuthPage.companyParams.companyNameLike" clearable size="default" style="width: 200px" />
              </el-form-item>
              <el-form-item>
                <search-button @click="handleAuthQuery" />
                <reset-button @click="resetAuthQuery" />
              </el-form-item>
            </el-form>
            <br />
            <el-row :gutter="10" class="mb8">
              <add-button @click="selectAuthInfo" text="选择" />
              <delete-button @click="handleDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
            </el-row>
            <el-table :data="configAuthPage.authCompanyDataList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="公司名称" align="center" prop="companyName" min-width="120" />
              <el-table-column label="公司编码" align="center" prop="companyCode" min-width="120" />
              <el-table-column label="简称" align="center" prop="companyShortname" min-width="120" />
              <el-table-column label="状态" align="center" min-width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                    {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="100" fixed="right">
                <template #default="scope">
                  <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.companyName + '?'" />
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="configAuthPage.total > 0"
              :total="configAuthPage.total"
              v-model:page="configAuthPage.companyParams.pageNum"
              v-model:limit="configAuthPage.companyParams.pageSize"
              @pagination="getCompanyAuthList"
            />
            <CompanyPicker ref="companyPicker" @ok="doSelected"></CompanyPicker>
          </el-tab-pane>
          <el-tab-pane :disabled="configAuthPage.enableAuth !== 'Y'" label="角色授权" name="04">
            <el-form :model="configAuthPage.roleParams" :inline="true" label-width="100px">
              <el-form-item label="角色名称：">
                <el-input v-model="configAuthPage.roleParams.roleNameLike" clearable size="default" style="width: 200px" />
              </el-form-item>
              <el-form-item>
                <search-button @click="handleAuthQuery" />
                <reset-button @click="resetAuthQuery" />
              </el-form-item>
            </el-form>
            <br />
            <el-row :gutter="10" class="mb8">
              <add-button @click="selectAuthInfo" text="选择" />
              <delete-button @click="handleDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
            </el-row>
            <el-table :data="configAuthPage.authRoleDataList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="角色名称" align="center" prop="roleName" min-width="120" />
              <el-table-column label="角色类型" align="center" prop="roleType" min-width="120" />
              <el-table-column label="角色权限字符串" align="center" prop="roleKey" min-width="120" />
              <el-table-column label="状态" align="center" min-width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                    {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="100" fixed="right">
                <template #default="scope">
                  <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.roleName + '?'" />
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="configAuthPage.total > 0"
              :total="configAuthPage.total"
              v-model:page="configAuthPage.roleParams.pageNum"
              v-model:limit="configAuthPage.roleParams.pageSize"
              @pagination="getRoleAuthList"
            />
            <RolePicker ref="rolePicker" @ok="doSelected"></RolePicker>
          </el-tab-pane>
          <el-tab-pane :disabled="configAuthPage.enableAuth !== 'Y'" label="岗位授权" name="05">
            <el-form :model="configAuthPage.postParams" :inline="true" label-width="100px">
              <el-form-item label="岗位名称：">
                <el-input v-model="configAuthPage.postParams.postNameLike" clearable size="default" style="width: 200px" />
              </el-form-item>
              <el-form-item>
                <search-button @click="handleAuthQuery" />
                <reset-button @click="resetAuthQuery" />
              </el-form-item>
            </el-form>
            <br />
            <el-row :gutter="10" class="mb8">
              <add-button @click="selectAuthInfo" text="选择" />
              <delete-button @click="handleDeleteBatch" :disabled="configAuthPage.selectAuthObjectList.length == 0" text="删除"></delete-button>
            </el-row>
            <el-table :data="configAuthPage.authPostDataList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" />
              <el-table-column label="岗位名称" align="center" prop="postName" min-width="120" />
              <el-table-column label="岗位类型" align="center" prop="postCode" min-width="120" />
              <el-table-column label="状态" align="center" min-width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'Y' ? 'success' : 'danger'" disable-transitions>
                    {{ scope.row.status === 'Y' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="100" fixed="right">
                <template #default="scope">
                  <text-delete-button @click="handleDelete(scope.row)" :title="'是否确认删除' + scope.row.postName + '?'" />
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="configAuthPage.total > 0"
              :total="configAuthPage.total"
              v-model:page="configAuthPage.postParams.pageNum"
              v-model:limit="configAuthPage.postParams.pageSize"
              @pagination="getPostAuthList"
            />
            <JobPicker ref="jobPicker" @ok="doSelected"></JobPicker>
          </el-tab-pane>
        </el-tabs>
        <br />
        <span style="color: red"
        >注：开启授权后，仅以上清单中 [人员] 或 [部门下人员] 或 [公司下人员] 或 [角色下人员] 或 [岗位下人员] 方可发起流程， 如果所有清单为空则无人可用发起流程即等同于流程禁用
        </span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="configAuthPage.open = false">关 闭</el-button>
        </div>
      </template>
    </drag-dialog>

    <!-- 配置事件 -->
    <drag-dialog
      :title="configEventPage.title" :close-on-click-modal="false" v-model="configEventPage.open" width="80%"
      append-to-body @close="cancelConfigEvent">
      <div class="scrollable-content">
        <div>【流程级】执行事件配置</div>
        <el-form :inline="true">
          <el-form-item label="流程发起后：">
            <el-input
              v-model="configEventPage.processStartedParticipant"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectUser(configEventPage, 'processStartedParticipant')">选择</el-button>
          </el-form-item>
          <el-form-item label="执行动作：">
            <el-select v-model="configEventPage.processStartedAction" placeholder="请选择" style="width: 150px">
              <el-option
                v-for="item in configEventPage.eventActions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form :inline="true">
          <el-form-item label="流程终止后：">
            <el-input
              v-model="configEventPage.processEndedParticipant"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectUser(configEventPage, 'processEndedParticipant')">选择</el-button>
          </el-form-item>
          <el-form-item label="执行动作：">
            <el-select v-model="configEventPage.processEndedAction" placeholder="请选择" style="width: 150px">
              <el-option
                v-for="item in configEventPage.eventActions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form :inline="true">
          <el-form-item label="流程完成后：">
            <el-input
              v-model="configEventPage.processCompletedParticipant"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectUser(configEventPage, 'processCompletedParticipant')">选择</el-button>
          </el-form-item>
          <el-form-item label="执行动作：">
            <el-select v-model="configEventPage.processCompletedAction" placeholder="请选择" style="width: 150px">
              <el-option
                v-for="item in configEventPage.eventActions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form :inline="true">
          <el-form-item label="到达节点时：">
            <el-input
              v-model="configEventPage.taskCreatedParticipant"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectUser(configEventPage, 'taskCreatedParticipant')">选择</el-button>
          </el-form-item>
          <el-form-item label="执行动作：">
            <el-select v-model="configEventPage.taskCreatedAction" placeholder="请选择" style="width: 150px">
              <el-option
                v-for="item in configEventPage.eventActions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form :inline="true">
          <el-form-item label="节点完成后：">
            <el-input
              v-model="configEventPage.taskCompletedParticipant"
              :disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectUser(configEventPage, 'taskCompletedParticipant')">选择</el-button>
          </el-form-item>
          <el-form-item label="执行动作：">
            <el-select v-model="configEventPage.taskCompletedAction" placeholder="请选择" style="width: 150px">
              <el-option
                v-for="item in configEventPage.eventActions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-divider></el-divider>
        <div>【节点级】通知配置</div>
        <el-table :data="configEventPage.nodeList" border>
          <el-table-column prop="taskName" label="节点名称"></el-table-column>
          <el-table-column prop="taskCreatedParticipant" label="到达节点时">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
                <el-input
                  v-model="scope.row.taskCreatedParticipant"
                  :disabled="true">
                </el-input>
                <el-button type="primary" size="default" @click="selectUser(scope.row, 'nodeTaskCreatedParticipant')">选择</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="taskCreatedAction" label="执行动作">
            <template #default="scope">
              <el-select v-model="scope.row.taskCreatedAction" placeholder="请选择">
                <el-option
                  v-for="item in configEventPage.eventActions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="taskCompletedParticipant" label="节点完成后">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
                <el-input
                  v-model="scope.row.taskCompletedParticipant"
                  :disabled="true">
                </el-input>
                <el-button type="primary" size="default" @click="selectUser(scope.row, 'nodeTaskCompletedParticipant')">选择</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="taskCompletedAction" label="执行动作">
            <template #default="scope">
              <el-select v-model="scope.row.taskCompletedAction" placeholder="请选择">
                <el-option
                  v-for="item in configEventPage.eventActions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="submitEventConfig" type="primary">确 定</el-button>
          <el-button @click="configEventPage.open = false">关 闭</el-button>
        </div>
      </template>
    </drag-dialog>

    <drag-dialog v-model="showAssigneeSelector" width="1200px">
      <assignee-selector v-model="candidateUsers" />
      <template #footer>
        <dialog-footer @ok="submit" @cancel="cancel"></dialog-footer>
      </template>
    </drag-dialog>

    <!-- 流程图 -->
    <drag-dialog
      :title="showFlowTitle"
      :close-on-click-modal="false"
      v-model="showFlowOpen"
      width="80%"
      append-to-body
    >
      <bpmnViewer v-if="isFlowable && showFlowOpen" :id="modelId" />
      <wf-static-image v-else :modelId="modelId" />
    </drag-dialog>

    <drag-dialog
      title="低代码页面选择"
      :close-on-click-modal="false"
      v-model="lowCodePageSelect.open"
      width="80%"
      append-to-body
    >
      <page-info in-dialog @select="handlePageSelected" style="max-height: 800px;overflow: auto;" />
    </drag-dialog>
  </div>
</template>

<script>
import { isArray, forIn } from 'lodash-es'
import {
  search,
  getConfigButtons,
  saveConfigButtons,
  getConfigUrls,
  saveConfigUrls,
  getConfigApprove,
  saveConfigApprove,
  delDeployment,
  insertAuthInfo,
  getEnableAuthByWfCode,
  searchAuthUser,
  searchAuthDept,
  searchAuthCompany,
  searchAuthRole,
  searchAuthPost,
  deleteAuthInfo,
  saveEnableAuth
} from '@wf/api/wf/deployment'

import { debounceWrapper } from '@/utils/zmids'
import bpmnViewer from '@wf/components/bpmnjs/bpmnViewer'
import WfStaticImage from '@/components/Zmids/Workflow/WfStaticImage.vue'
import pageInfo from '@code/views/code/page/info/index.vue'
import OrgPicker from '@/components/Zmids/OrgPicker/index.vue'
import DeptPicker from '@/components/Zmids/DepartmentPicker/index.vue'
import CompanyPicker from '@/components/Zmids/CompanyName/index.vue'
import RolePicker from '@/components/Zmids/RolePicker/index.vue'
import JobPicker from '@/components/Zmids/JobPicker/index.vue'
import AssigneeSelector from "@/platform/wf/components/bpmnjs/components/common/AssigneeSelector.vue";
import {getEventConfigByWfCode, saveConfigEvent} from "@/platform/wf/api/wf/deployment.js";


export default {
  name: 'WfManagerDeployment',
  components: {AssigneeSelector,  WfStaticImage, pageInfo, OrgPicker, DeptPicker, CompanyPicker, RolePicker, JobPicker, bpmnViewer },
  data() {
    return {
      // 模型ID
      modelId: '',
      // 部署ID
      deploymentId: '',
      // 部署信息：this.initDeploymentInfo()
      deploymentInfo: {},
      // 配置按钮页面：this.initConfigButtonsPage()
      configButtonsPage: {},
      // 配置审批页面：this.initConfigUrlsPage()
      configUrlsPage: {},
      //配置approve
      configApprovePage: {},
      // 配置授权页面
      configAuthPage: {},
      // 配置事件页面
      configEventPage: {},
      // 遮罩层
      loading: true,
      currentPage: 1,
      pagesize: 10,
      deploymentList: [],
      // 总条数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      showFlowTitle: '',
      showFlowOpen: false,
      //图片流
      imageContent: '',
      // 配置项展开
      activeNames: ['1', '2', '3', '4'],
      // 暂存row
      editRow: null,
      editRowType: "taskCreatedParticipant",
      candidateUsers: [],
      showAssigneeSelector: false,
      // 低代码页面选择
      lowCodePageSelect:{
        open: false,
        type: '', // flow流程级,node节点级
        for: '', // 记录页面选择的对应属性
        taskId: '' // 如果是节点级，需要记录节点的taskId
      }
    }
  },
  computed: {
    isFlowable(){
      return import.meta.env.VITE_FLOW_TYPE == 'flowable'
    }
  },
  created() {
    this.initConfigButtonsPage()
    this.initConfigUrlsPage()
    this.initConfigApprovePage()
    this.initConfigAuthPage()
    this.initConfigEventPage()
    this.search()
  },

  methods: {
    //部署管理列表查询
    search: debounceWrapper(function () {
      this.loading = true
      search(this.addDateRange(this.queryParams)).then((response) => {
        this.deploymentList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    }),
    // 初始化编辑的部署信息
    initDeploymentInfo() {
      this.imageContent = ''
      this.deploymentInfo = {
        modelId: '',
        key: '',
        name: '',
        buttons: [],
        elements: []
      }
    },
    // 初始化配置按钮页面参数
    initConfigButtonsPage() {
      this.initDeploymentInfo()
      this.configButtonsPage = {
        open: false,
        title: '配置按钮',
        checkedButtons: {}
      }
    },
    // 初始化配置URL页面参数
    initConfigUrlsPage() {
      this.initDeploymentInfo()
      this.configUrlsPage = {
        open: false,
        title: '配置页面',
        approveUrl: '',
        approveFrameUrl: '',
        doneViewUrl: '',
        doneViewFrameUrl: '',
        wfApproveFrameUrl: '',
        wfApproveUrl: '',
        wfDoneViewUrl: '',
        wfDoneViewFrameUrl: '',
        nodeApproveUrl: {},
        nodeApproveFrameUrl: {},
        nodeDoneViewUrl: {},
        nodeDoneViewFrameUrl: {}
      }
    },
    // 初始化配置APPROVE页面参数
    initConfigApprovePage() {
      this.initDeploymentInfo()
      this.configApprovePage = {
        open: false,
        title: '审批配置',
        canBatchApprove: {},
        candidateSelectType: {},
        messageSendType: {},
        canBatchOptions: [],
        selectTypeOptions: [],
        sendTypeOptions: []
      }
      this.getDicts('sys_yes_no').then((response) => {
        this.configApprovePage.canBatchOptions = response.data
      })
      this.getDicts('wf_candidate_select_type').then((response) => {
        this.configApprovePage.selectTypeOptions = response.data
      })
      this.getDicts('wf_message_send_type').then((response) => {
        this.configApprovePage.sendTypeOptions = response.data
      })
    },
    // 初始化配置授权页面参数
    initConfigAuthPage() {
      this.initDeploymentInfo()
      this.configAuthPage = {
        open: false,
        title: '授权配置',
        enableAuth: 'N',
        total: 0,
        authUserDataList: [], // 人员授权列表数据
        authDeptDataList: [], // 部门授权列表数据
        authCompanyDataList: [], // 公司授权列表数据
        authRoleDataList: [], // 角色授权列表数据
        authPostDataList: [], // 岗位授权列表数据
        selectAuthObjectList: [], // 多选列表
        // 授权通用参数map
        dataParams: {
          wfCode: '',
          authType: '',
          authObjectIds: ''
        },
        // 人员授权参数
        userParams: {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '01',
          loginNameLike: '',
          userNameLike: ''
        },
        // 部门授权参数
        deptParams: {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '02',
          deptNameLike: ''
        },
        // 公司授权参数
        companyParams: {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '03',
          companyNameLike: ''
        },
        // 角色授权参数
        roleParams: {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '04',
          roleNameLike: ''
        },
        // 岗位授权参数
        postParams: {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '05',
          postNameLike: ''
        },
      }
    },
    // 初始化配置事件页面参数
    initConfigEventPage(){
      this.initDeploymentInfo()
      this.configEventPage = {
        open: false,
        title: '事件配置',
        wfCode: '',
        eventActions: {},
        nodeList: []
      }
      this.getDicts('wf_event_action').then((response) => {
        this.configEventPage.eventActions = response.data
      })
    },
    // 设置部署信息
    setDeploymentInfo(response) {
      this.deploymentInfo = {
        modelId: response.data.modelId,
        key: response.data.key,
        name: response.data.name,
        buttons: response.data.buttons || [],
        elements: response.data.elements || []
      }
    },
    //配置按钮
    configButtons: debounceWrapper(function (row) {
      this.loading = true
      this.modelId = row.id
      this.deploymentId = row.deploymentId
      getConfigButtons(this.deploymentId).then((response) => {
        this.loading = false
        this.setDeploymentInfo(response)
        this.configButtonsPage = {
          open: true,
          title: '配置按钮 - ' + this.deploymentInfo.name,
          checkedButtons: {}
        }
        this.deploymentInfo.elements.forEach((e) => {
          for (var p in e.params) {
            this.configButtonsPage.checkedButtons[e.taskId + ':' + p] = true
          }
        })
      })
    }),
    // 配置按钮页面提交
    submitHandlerButtons: debounceWrapper(function () {
      this.loading = true
      var data = {}
      for (var key in this.configButtonsPage.checkedButtons) {
        // 选中状态
        if (this.configButtonsPage.checkedButtons[key] === true) {
          var keys = key.split(':')
          if (!isArray(data[keys[0]])) {
            data[keys[0]] = []
          }
          data[keys[0]].push(keys[1])
        }
      }
      var buttons = []
      forIn(data, function (v, k) {
        buttons.push(k + ':' + v.join(','))
      })
      saveConfigButtons(this.deploymentId, buttons.join('##')).then((response) => {
        if (response.success === true) {
          this.msgSuccess('保存成功')
          this.initConfigButtonsPage()
          this.search()
        }
        this.loading = false
      })
    }),
    // 配置按钮页面取消
    cancelConfigButtons() {
      this.initConfigButtonsPage()
    },

    //配置审批页面
    configUrls: debounceWrapper(function (row) {
      this.loading = true
      this.modelId = row.id
      this.deploymentId = row.deploymentId
      getConfigUrls(this.deploymentId).then((response) => {
        this.loading = false
        this.setDeploymentInfo(response)
        this.configUrlsPage = {
          open: true,
          title: '页面配置 - ' + (this.deploymentInfo.name || ''),
          approveUrl: response.data.approveUrl || '',
          approveFrameUrl: response.data.approveFrameUrl || '',
          doneViewUrl: response.data.doneViewUrl || '',
          doneViewFrameUrl: response.data.doneViewFrameUrl || '',
          wfApproveFrameUrl: response.data.wfApproveFrameUrl || '',
          wfApproveUrl: response.data.wfApproveUrl || '',
          wfDoneViewUrl: response.data.wfDoneViewUrl || '',
          wfDoneViewFrameUrl: response.data.wfDoneViewFrameUrl || '',
          wfStartViewUrl: response.data.wfStartViewUrl || '',
          wfStartViewFrameUrl: response.data.wfStartViewFrameUrl || '',
          nodeApproveUrl: {},
          nodeApproveFrameUrl: {},
          nodeDoneViewUrl: {},
          nodeDoneViewFrameUrl: {}
        }
        // 初始化节点输入框的值
        this.deploymentInfo.elements.forEach((e) => {
          this.configUrlsPage.nodeApproveUrl[e.taskId] = e.approveUrl
          this.configUrlsPage.nodeApproveFrameUrl[e.taskId] = e.approveFrameUrl
          this.configUrlsPage.nodeDoneViewUrl[e.taskId] = e.doneViewUrl
          this.configUrlsPage.nodeDoneViewFrameUrl[e.taskId] = e.doneViewFrameUrl
        })
      })
    }),
    // 配置URL页面提交按钮
    submitHandlerUrls: debounceWrapper(function () {
      this.loading = true
      const list = []
      // 发起查看页面配置
      list.push({
        startViewUrl: this.configUrlsPage.wfStartViewUrl,
        startViewFrameUrl: this.configUrlsPage.wfStartViewFrameUrl
      })
      // 流程级待办和已办配置
      list.push({
        approveUrl: this.configUrlsPage.wfApproveUrl,
        approveFrameUrl: this.configUrlsPage.wfApproveFrameUrl,
        doneViewUrl: this.configUrlsPage.wfDoneViewUrl,
        doneViewFrameUrl: this.configUrlsPage.wfDoneViewFrameUrl
      })
      // 节点级待办和已办配置
      this.deploymentInfo.elements.forEach((e) => {
        list.push({
          taskDefinitionKey: e.taskId,
          approveUrl: this.configUrlsPage.nodeApproveUrl[e.taskId],
          approveFrameUrl: this.configUrlsPage.nodeApproveFrameUrl[e.taskId],
          doneViewUrl: this.configUrlsPage.nodeDoneViewUrl[e.taskId],
          doneViewFrameUrl: this.configUrlsPage.nodeDoneViewFrameUrl[e.taskId]
        })
      })

      saveConfigUrls({ deploymentId: this.deploymentId, urls: list }).then((response) => {
        this.loading = false
        this.msgSuccess('新增成功')
        this.initConfigUrlsPage()
        this.search()
      })
    }),
    // 配置按钮页面取消
    cancelConfigUrls() {
      this.initConfigUrlsPage()
    },

    //配置Approve页面
    configApprove: debounceWrapper(function (row) {
      this.loading = true
      this.modelId = row.id
      this.deploymentId = row.deploymentId
      getConfigApprove(this.deploymentId).then((response) => {
        this.loading = false
        this.setDeploymentInfo(response)
        this.configApprovePage.open = true
        this.configApprovePage.title = '审批配置 - ' + (this.deploymentInfo.name || '')
        this.configApprovePage.canBatchApprove = {}
        this.configApprovePage.candidateSelectType = {}
        this.configApprovePage.messageSendType = {}
        // 初始化节点输入框的值
        this.deploymentInfo.elements.forEach((e) => {
          this.configApprovePage.canBatchApprove[e.taskId] = e.canBatchApprove
          this.configApprovePage.candidateSelectType[e.taskId] = e.candidateSelectType
          this.configApprovePage.messageSendType[e.taskId] = e.messageSendType
        })
      })
    }),
    // 配置Approve页面提交按钮
    submitHandlerApprove: debounceWrapper(function () {
      this.loading = true
      const list = []
      this.deploymentInfo.elements.forEach((e) => {
        list.push({
          taskDefinitionKey: e.taskId,
          canBatchApprove: this.configApprovePage.canBatchApprove[e.taskId],
          candidateSelectType: this.configApprovePage.candidateSelectType[e.taskId],
          messageSendType: this.configApprovePage.messageSendType[e.taskId]
        })
      })
      saveConfigApprove({ deploymentId: this.deploymentId, datas: list }).then((response) => {
        this.loading = false
        this.msgSuccess('保存成功')
        this.initConfigApprovePage()
        this.search()
      })
    }),
    // 配置Approve页面取消
    cancelConfigApprove() {
      this.initConfigApprovePage()
    },

    // 配置授权页面
    configAuth: debounceWrapper(function (row) {
      this.loading = true;
      this.configAuthPage.dataParams.wfCode = row.key;
      // 判断该流程授权是否打开
      getEnableAuthByWfCode(this.configAuthPage.dataParams.wfCode).then(res => {
        this.configAuthPage.enableAuth = res.data;
        // 如果打开，进行数据查询
        if (this.configAuthPage.enableAuth === "Y"){
          this.getUserAuthList();
        }
      })
      this.configAuthPage.open = true;
      this.loading = false;
    }),

    // 获取人员授权列表初始信息
    getUserAuthList(){
      // 初始授权列表为人员授权列表01
      this.configAuthPage.dataParams.authType = "01";
      this.configAuthPage.userParams.wfCode = this.configAuthPage.dataParams.wfCode;
      searchAuthUser(this.configAuthPage.userParams).then(res => {
        this.configAuthPage.authUserDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取部门授权列表初始信息
    getDeptAuthList(){
      this.configAuthPage.deptParams.wfCode = this.configAuthPage.dataParams.wfCode;
      searchAuthDept(this.configAuthPage.deptParams).then(res => {
        this.configAuthPage.authDeptDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取公司授权列表初始信息
    getCompanyAuthList(){
      this.configAuthPage.companyParams.wfCode = this.configAuthPage.dataParams.wfCode;
      searchAuthCompany(this.configAuthPage.companyParams).then(res => {
        this.configAuthPage.authCompanyDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取角色授权列表初始信息
    getRoleAuthList(){
      this.configAuthPage.roleParams.wfCode = this.configAuthPage.dataParams.wfCode;
      searchAuthRole(this.configAuthPage.roleParams).then(res => {
        this.configAuthPage.authRoleDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 获取岗位授权列表初始信息
    getPostAuthList(){
      this.configAuthPage.postParams.wfCode = this.configAuthPage.dataParams.wfCode;
      searchAuthPost(this.configAuthPage.postParams).then(res => {
        this.configAuthPage.authPostDataList = res.data.list;
        this.configAuthPage.total = res.data.total;
      });
    },

    // 配置授权页面关闭
    cancelConfigAuth(){
      this.initConfigAuthPage()
    },

    // 切换开启/关闭授权回调
    handleEnableAuth(value){
      // 构建方法参数
      const openParams = {
        wfCode: this.configAuthPage.dataParams.wfCode,
        enableAuth: '',
        withDelete: ''
      };
      if (value === 'Y'){
        this.$confirm('此操作将开启授权, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.configAuthPage.enableAuth = value;
          openParams.enableAuth = value;
          openParams.withDelete = 'N';
          saveEnableAuth(openParams).then(res => {
            this.getUserAuthList(); // 开启后初始化人员授权列表
            this.$message({
              type: 'success',
              message: '开启成功!'
            });
          });
        }).catch(() => {
          this.configAuthPage.dataParams.authType = '';
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
      if (value === 'N'){
        this.$confirm('此操作将关闭授权，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$confirm('是否保留已有的授权信息？', '提示', {
            confirmButtonText: '保留',
            cancelButtonText: '不保留',
            type: 'warning'
          }).then(() => {
            this.configAuthPage.enableAuth = value;
            this.configAuthPage.dataParams.authType = '';
            openParams.enableAuth = value;
            openParams.withDelete = 'N';
            saveEnableAuth(openParams).then(res => {
              this.$message({
                type: 'success',
                message: '关闭成功，保留已有的授权信息'
              });
            });
          }).catch(() => {
            this.configAuthPage.enableAuth = value;
            this.configAuthPage.dataParams.authType = '';
            openParams.enableAuth = value;
            openParams.withDelete = 'Y';
            saveEnableAuth(openParams).then(res => {
              this.$message({
                type: 'success',
                message: '关闭成功，清空已有的授权信息'
              });
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消关闭'
          });
        });
      }
    },

    // 切换授权类型回调
    handleAuthType(tab, event) {
      // 使用 Vue.nextTick 等待 DOM 和数据更新完毕后再执行逻辑
      this.$nextTick(() => {
        // 清空选择的id列表
        this.configAuthPage.selectAuthObjectList = [];
        this.configAuthPage.dataParams.authObjectIds = '';
        this.resetAuthQuery();
      });
    },

    // 通用授权列表查询
    handleAuthQuery: debounceWrapper(function() {
      if (this.configAuthPage.dataParams.authType === "01"){
        this.getUserAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "02"){
        this.getDeptAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "03"){
        this.getCompanyAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "04"){
        this.getRoleAuthList();
      }
      if (this.configAuthPage.dataParams.authType === "05"){
        this.getPostAuthList();
      }
    }),

    // 通用授权列表多选回调
    handleSelectionChange(value){
      this.configAuthPage.selectAuthObjectList = value;
    },

    // 通用打开选择人员弹框
    selectAuthInfo: debounceWrapper(function(){
      if (this.configAuthPage.dataParams.authType === "01"){
        this.$refs.orgPicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "02"){
        this.$refs.deptPicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "03"){
        this.$refs.companyPicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "04"){
        this.$refs.rolePicker.show();
      }
      if (this.configAuthPage.dataParams.authType === "05"){
        this.$refs.jobPicker.show();
      }
    }),

    // 选择授权信息后回调
    doSelected(list){
      if (this.configAuthPage.dataParams.authType === '01') {
        // 使用 map 提取每个 user 的 userId
        const userIds = list.map(user => user.userId);
        // 将 userId 数组转换为逗号分隔的字符串
        this.configAuthPage.dataParams.authObjectIds = userIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '02'){
        const deptIds = list.map(dept => dept.deptId);
        this.configAuthPage.dataParams.authObjectIds = deptIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '03'){
        const companyIds = list.map(company => company.companyId);
        this.configAuthPage.dataParams.authObjectIds = companyIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '04'){
        const roleIds = list.map(role => role.roleId);
        this.configAuthPage.dataParams.authObjectIds = roleIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '05'){
        const postIds = list.map(post => post.postId);
        this.configAuthPage.dataParams.authObjectIds = postIds.join(',');
      }

      // 插入列表信息
      insertAuthInfo(this.configAuthPage.dataParams).then(res => {
        this.$message.success("授权信息添加成功，您可在列表中查看相关详情！");
        // 插入成功后清空授权id列表
        this.configAuthPage.dataParams.authObjectIds = '';
        this.handleAuthQuery();
      })
    },

    // 通用授权列表参数重置
    resetAuthQuery() {
      if (this.configAuthPage.dataParams.authType === '01') {
        this.configAuthPage.userParams = {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '01',
          loginNameLike: '',
          userNameLike: ''
        };
        this.getUserAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '02') {
        this.configAuthPage.deptParams = {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '02',
          deptNameLike: ''
        };
        this.getDeptAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '03') {
        this.configAuthPage.companyParams = {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '03',
          companyNameLike: ''
        };
        this.getCompanyAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '04') {
        this.configAuthPage.roleParams = {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '04',
          roleNameLike: ''
        };
        this.getRoleAuthList();
      }
      if (this.configAuthPage.dataParams.authType === '05') {
        this.configAuthPage.postParams = {
          pageNum: 1,
          pageSize: 10,
          wfCode: '',
          authType: '05',
          postNameLike: ''
        };
        this.getPostAuthList();
      }
    },

    // 批量删除授权信息
    handleDeleteBatch: debounceWrapper(function(){
      if (this.configAuthPage.dataParams.authType === '01'){
        // 使用 map 提取每个 user 的 userId
        const userIds = this.configAuthPage.selectAuthObjectList.map(user => user.userId);
        // 将 userId 数组转换为逗号分隔的字符串
        this.configAuthPage.dataParams.authObjectIds = userIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '02'){
        const deptIds = this.configAuthPage.selectAuthObjectList.map(dept => dept.deptId);
        this.configAuthPage.dataParams.authObjectIds = deptIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '03'){
        const companyIds = this.configAuthPage.selectAuthObjectList.map(company => company.companyId);
        this.configAuthPage.dataParams.authObjectIds = companyIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '04'){
        const roleIds = this.configAuthPage.selectAuthObjectList.map(role => role.roleId);
        this.configAuthPage.dataParams.authObjectIds = roleIds.join(',');
      }
      if (this.configAuthPage.dataParams.authType === '05'){
        const postIds = this.configAuthPage.selectAuthObjectList.map(post => post.postId);
        this.configAuthPage.dataParams.authObjectIds = postIds.join(',');
      }

      // 批量删除
      deleteAuthInfo(this.configAuthPage.dataParams).then(res => {
        this.$message.success("删除成功！");
        // 清空选择列表
        this.configAuthPage.selectAuthObjectList = [];
        this.configAuthPage.dataParams.authObjectIds = '';
        this.handleAuthQuery();
      })
    }),

    // 删除授权信息
    handleDelete: debounceWrapper(function(row) {
      if (this.configAuthPage.dataParams.authType === '01'){
        this.configAuthPage.dataParams.authObjectIds = row.userId;
      }
      if (this.configAuthPage.dataParams.authType === '02'){
        this.configAuthPage.dataParams.authObjectIds = row.deptId;
      }
      if (this.configAuthPage.dataParams.authType === '03'){
        this.configAuthPage.dataParams.authObjectIds = row.companyId;
      }
      if (this.configAuthPage.dataParams.authType === '04'){
        this.configAuthPage.dataParams.authObjectIds = row.roleId;
      }
      if (this.configAuthPage.dataParams.authType === '05'){
        this.configAuthPage.dataParams.authObjectIds = row.postId;
      }

      deleteAuthInfo(this.configAuthPage.dataParams).then(res => {
        this.$message.success("删除成功！");
        // 清空选择列表
        this.configAuthPage.dataParams.authObjectIds = '';
        this.handleAuthQuery();
      })
    }),

    // 查看流转过程
    showFlowStaticImg(row) {
      this.showFlowTitle = '查看流程图'
      this.showFlowOpen = true
      this.modelId = row.id
    },
    //下载BPMN20
    downloadHandler: debounceWrapper(function (row) {
      this.downloadUrl(
        import.meta.env.VITE_APP_GATEWAY_URL + '/wf/manager/deployment/download/' + row.deploymentId
      )
      this.msgSuccess('正在启动下载......')
    }),
    //撤销发布
    revokePublish: debounceWrapper(function (row) {
      this.$confirm(
        '是否确认撤销已发布的流程[ ' +
          row.name +
          '(' +
          row.key +
          ')' +
          ' ]，撤销后流程将不可用，可通过流程定义再次发布?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.loading = true
          return delDeployment(row.id)
        })
        .then(() => {
          this.loading = false
          this.msgSuccess('撤销成功')
          this.search()
        })
        .catch(() => {})
    }),
    // 配置按钮操作
    handleConf: debounceWrapper(function (command, row) {
      if ('confBut' === command) {
        this.configButtons(row)
      } else if ('confUrl' === command) {
        this.configUrls(row)
      } else if ('confApprove' === command) {
        this.configApprove(row)
      } else if ('confAuth' === command) {
        this.configAuth(row)
      } else if ('confEvent' === command){
        this.configEvent(row)
      }
    }),
    handlePageSelectOpen: debounceWrapper(function (type, data, taskId){
      this.lowCodePageSelect.open = true
      this.lowCodePageSelect.for = data
      this.lowCodePageSelect.type = type
      if(taskId){
        this.lowCodePageSelect.taskId = taskId
      }
    }),
    handlePageSelected: debounceWrapper(function (pageId){
      console.log('page!',pageId)
      this.lowCodePageSelect.open = false
      const url = `/anvil-code-low-common/views/page/filling/flowFilling/${pageId}`
      if(this.lowCodePageSelect.type == 'flow'){
        this.configUrlsPage[this.lowCodePageSelect.for] = url
      }else{
        this.configUrlsPage[this.lowCodePageSelect.for][this.lowCodePageSelect.taskId] = url
      }
    }),

    // 配置事件界面
    configEvent: debounceWrapper(function (row) {
      this.loading = true;
      this.configEventPage.wfCode = row.key;
      // 判断该流程授权是否打开
      getEventConfigByWfCode(this.configEventPage.wfCode).then(res => {
        this.configEventPage = {
          ... this.configEventPage,
          ... res.data
        };
       this.configEventPage.open = true;
     })
      this.loading = false;
    }),

    // 配置事件页面关闭
    cancelConfigEvent(){
      this.initConfigEventPage()
    },
    // 提交事件配置
    submitEventConfig(){
      var configs = this.configEventPage
      delete configs.eventActions
      delete configs.open
      delete configs.title
      saveConfigEvent(configs).then(res => {
        if (res.code === '200'){
          this.msgSuccess("事件配置保存成功")
        }else {
          this.msgError(res.msg)
        }
      })
    },

    // 选择人员
    selectUser(row, type){
      this.editRow = row
      this.editRowType = type
      this.showAssigneeSelector = true
    },

    cancel() {
      this.showAssigneeSelector = false;
    },

    submit() {
      if (this.editRowType === 'nodeTaskCreatedParticipant'){
        this.editRow.taskCreatedParticipant = this.candidateUsers.map((user) => user.value).join(',');
      } else if( this.editRowType === 'nodeTaskCompletedParticipant'){
        this.editRow.taskCompletedParticipant =  this.candidateUsers.map((user) => user.value).join(',');
      } else if (this.editRowType === 'processStartedParticipant'){
        this.editRow.processStartedParticipant = this.candidateUsers.map((user) => user.value).join(',');
      } else if (this.editRowType === 'processEndedParticipant'){
        this.editRow.processEndedParticipant = this.candidateUsers.map((user) => user.value).join(',');
      } else if (this.editRowType === 'processCompletedParticipant'){
        this.editRow.processCompletedParticipant = this.candidateUsers.map((user) => user.value).join(',');
      } else if (this.editRowType === 'taskCreatedParticipant'){
        this.editRow.taskCreatedParticipant = this.candidateUsers.map((user) => user.value).join(',');
      } else if (this.editRowType === 'taskCompletedParticipant'){
        this.editRow.taskCompletedParticipant = this.candidateUsers.map((user) => user.value).join(',');
      }
      this.cancel();
    }
  }
}
</script>

<style lang="scss" scoped>
.node-table {
  .label {
    text-align: center;
    height: 36px;
    line-height: 36px;
  }
  .label-text {
    line-height: 36px;
    font-weight: 700;
    font-size: 14px;
    color: #606266;
  }

  .el-row {
    margin-bottom: 8px;
  }
}

.el-form {
  .el-divider {
    margin: 4px 0;
  }
  .el-form-item {
    margin-bottom: 4px;
  }
  .el-collapse-item__content {
    padding-bottom: 4px;
  }
}

.operation {
  display: flex;
  align-items: center;

  &-drop {
    display: flex;
    align-items: center;
  }
}

.scrollable-content {
  max-height: 600px; /* 根据需要调整最大高度 */
  overflow-y: auto; /* 当内容超出高度时显示滚动条 */
}
</style>
